package com.homedo.odin.solution.service;

import com.homedo.core.common.base.service.BaseService;
import com.homedo.core.common.util.ListSortUtil;
import com.homedo.odin.solution.dao.AttachmentMapper;
import com.homedo.odin.solution.model.dto.PdfImagesResponseBean;
import com.homedo.odin.solution.model.entity.Attachment;
import com.homedo.odin.solution.service.common.HomedoService;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p> 文件附件信息表 服务实现类 </p>
 *
 * @author HarveyDing
 * @since 2018-03-08
 */
@Service
public class AttachmentServiceImpl extends BaseService<AttachmentMapper, Attachment> {

    @Autowired
    HomedoService homedoService;

    public void addAttachment(Attachment attachment) {
        baseMapper.insert(attachment);
    }

    public void delAttachmentByBusinessId(Long businessId, Integer businessType) {
        baseMapper.delAttachmentByBusinessId(businessId, businessType);
    }

    public List<Attachment> queryAttachmentByBusinessId(Long solutionId, Integer businessType) {
        return baseMapper.queryAttachmentByBusinessId(solutionId, businessType);
    }

    /**
     * 增加附件
     *
     * @param attachment 附件地址字符串
     * @param businessId 业务id
     * @param businessType 业务类型 1：方案 2：行业规范
     */
    public void addAttachment(String attachment, Long businessId, int businessType) {
        if (attachment != null && attachment != "") {
            String[] attachments = attachment.split("\\|\\|");
            Attachment addAttachment;
            for (String url : attachments) {
                addAttachment = new Attachment();
                addAttachment.setBusinessId(businessId);
                addAttachment.setBusinessType(businessType);
                addAttachment.setAttachmentUrl(url);

                List<PdfImagesResponseBean> images = homedoService.getPdfToImages(url);
                //对list排序
                ListSortUtil.sort(images, "id", true);

                String picUrl = images.stream().map(pdfImagesResponseBean -> pdfImagesResponseBean.getFileName())
                        .collect(Collectors.joining("||"));
                picUrl = StringUtils.isNotBlank(picUrl) ? picUrl.substring(2) : picUrl;
                if (StringUtils.isBlank(picUrl)) {
                    continue;
                }
                addAttachment.setAttachmentPicture(picUrl);
                addAttachment(addAttachment);
            }
        }
    }

    public Attachment getAttachmentInfoById(Integer id) {
        return baseMapper.selectById(id);
    }
}
